<!--
 * @Description: 花了还有无感结算页面
 * @Author: Kerwin
 * @Date: 2025-05-26 14:46:49
 * @LastEditTime: 2025-11-25 10:46:32
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="physicalShopCheck">
    <!-- 加载状态 -->
    <view v-if="pageLoading" class="loading-mask">
      <u-loading mode="circle" size="60" color="#2979ff"></u-loading>
      <text class="loading-text">加载中...</text>
    </view>

    <u-navbar
      :title-bold="false"
      v-if="!isWeChatBrowser"
      :is-back="false"
      color="#333"
      :background="{ backgroundColor: '#f9c9ae' }"
    >
      <template #right>
        <view style="margin: 0 20rpx" @click="clearUser">
          <u-icon name="man-delete" color="#999999" size="42"></u-icon>
        </view>
      </template>
    </u-navbar>
    <!-- 头部 -->
    <view class="topTitLe">
      <view class="leftTitle">
        <view style="font-weight: 700; font-size: 32rpx; margin-bottom: 20rpx"
          >消费总金额</view
        >
        <view style="color: #999">请询问金额后提交</view>
      </view>
      <view class="rightTitle">
        <u-image width="180rpx" height="150rpx" :src="moneyIcon"></u-image>
      </view>
    </view>
    <!-- 商户信息 -->
    <view class="shopBox">
      <text class="name"
        ><u-icon
          size="40"
          style="vertical-align: middle"
          :name="shopIcon1"
        ></u-icon>
        {{ info.name }}</text
      >
      <view class="inptBox">
        <u-input
          v-model="money"
          v-input-decimal2
          type="digit"
          inputmode="decimal"
          focus
          pattern="number"
          placeholder="¥ 0.00"
          input-align="center"
          :custom-style="{
            fontSize: '52rpx'
          }"
          :disabled="inptDisabled"
        />
        <text class="unit">(元)</text>
      </view>
      <view class="yt-list-cell shape2">
        <view class="cell-tit">
          抵用券抵扣：<text class="red"
            >（本次最多使用{{ scoreMax }}积分，可抵扣{{ scoreMax }}元）</text
          ></view
        >
        <view class="cell-tip">
          <view class="wallet"> 抵用券剩余：{{ userScore }}</view>
          <view class="right" style="width: 250rpx">
            <u-input
              class="inputBox"
              :disabled="!userScore && userScore < 0"
              v-input-decimal
              placeholder="请输入抵扣积分"
              type="digit"
              v-model="score_consumption"
              @blur="onScoreChange"
              :border="true"
            />
          </view>
        </view>
        <view class="hjfScore"> 绿色积分剩余：{{ hjfUserScor }}</view>
      </view>

      <view
        class="radioBox"
        v-if="info.shopMoneyRules && info.shopMoneyRules.length > 1"
      >
        <u-radio-group
          v-model="moneyRuleId"
          @change="radioGroupChange"
          :wrap="true"
        >
          <u-radio
            v-for="(item, index) in info.shopMoneyRules"
            :key="index"
            :name="item.moneyRuleId"
          >
            {{ item.userMoneyRuleName }}
          </u-radio>
        </u-radio-group>
      </view>
    </view>
    <!-- 结算 -->
    <u-button
      :disabled="!info.shopId"
      class="hy-btn"
      type="primary"
      ripple
      @click="toPayment"
    >
      确认付款
    </u-button>
    <view class="hy-link" v-if="bindPhone" @click="toBindPhone">
      绑定手机号
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch, nextTick } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
//存储
import { storeToRefs } from 'pinia'
import { useConfigStore, useUserStore } from '@/store'
//api
import { enumAll, moneyApi, orderApi, productApi, userApi } from '@/api'
//工具
import {
  getQueryVariable,
  getQueryObject,
} from '@/utils/common'
import debounce from 'lodash/debounce'
//图片
import moneyIcon from '@/static/hlhy/money2.png'
import shopIcon1 from '@/static/hlhy/shopIcon1.png'

//初始数据
const configStore = useConfigStore()
const userStore = useUserStore()
const { isWeChatBrowser } = storeToRefs(configStore)
const { accessToken, useShareCode } = storeToRefs(userStore)

const info = reactive<any>({
  name: '',
  shopId: '',
  shopMoneyRules: []
})
const mode = ref()
const createTime = ref()
const money = ref()
const orderData = ref<any>({
  remark: ''
})
const productSku = ref()
const moneyRuleId = ref(null)
const userInfo = userStore.userInfo
const userPhone = ref<any>(null)
const bindPhone = ref(false)
const login_success = ref<any>({ status: false })
const isHjfShop = ref(false)
const score_consumption = ref(0)
const userScore = ref(0)
const hjfUserScor = ref(0)
const maxUserScor = ref(0)
const whiteList = ref(0)
const pageLoading = ref(false)
const inptDisabled = ref(false)
const btnColor = ref('2979ff')

let _userScore = 0

// 创建订单
async function creatOrder() {
  console.log('提交的订单信息', orderData.value)
  try {
    const { data } = await orderApi.orderAdd(orderData.value)
    console.log('订单创建成功==>', data)
    if (data) {
      location.href = `https://api.mylkjgs.com/?token=${accessToken.value}&orderId=${data.id}`
    }
  } catch (err) {
    console.log(err)
  }
  uni.hideLoading()
}

const onScoreChange = (e: number) => {
  e = Number(e)
  if (!money.value) {
    uni.showToast({
      icon: 'none',
      title: '请先输入支付金额'
    })
    score_consumption.value = 0
    return
  }
  if (e < 0) {
    uni.showToast({
      icon: 'none',
      title: '积分有误'
    })
    score_consumption.value = scoreMax.value
    userScore.value = Math.floor((maxUserScor.value - scoreMax.value) * 10) / 10
  } else if (e <= scoreMax.value) {
    score_consumption.value = e
    userScore.value = Math.floor((maxUserScor.value - e) * 10) / 10
  } else {
    score_consumption.value = scoreMax.value
    userScore.value = Math.floor((maxUserScor.value - scoreMax.value) * 10) / 10
    uni.showToast({
      icon: 'none',
      title: '积分有误'
    })
  }
}

// 创建防抖版本的 creatOrder 函数
const debouncedCreatOrder = debounce(creatOrder, 500)

async function toPayment() {
  if (!money.value) {
    uni.showToast({
      icon: 'none',
      title: '请输入支付金额'
    })
    return
  }
  if (money.value <= 0) {
    uni.showToast({
      icon: 'none',
      title: '最低金额需大于0元'
    })
    return
  }
  if (score_consumption.value > scoreMax.value) {
    uni.showToast({
      icon: 'none',
      title: '最多只能抵扣' + scoreMax.value + '元'
    })
    return
  }

  uni.showLoading({ title: '', mask: true })
  try {
    await getShopSku()
    if (uni.getStorageSync('shareCode') && useShareCode.value) {
      orderData.value.orderProductSkus[0].externalData = {
        userShareCode: uni.getStorageSync('shareCode')
      }
    }
    debouncedCreatOrder()
  } catch (err) {
    uni.hideLoading()
  }
}

//获取商铺sku
const getShopSku = async () => {
  const { data } = await productApi.getShopProductSkuList({
    detail: false,
    dynamicPrice: true,
    shopId: info.shopId
  })
  if (data.records) {
    productSku.value = data.records[0]
    orderData.value.orderProductSkus = [
      {
        count: 1,
        money: money.value,
        shopProductSkuId: productSku.value.id,
        moneyRuleId: moneyRuleId.value,
        dynamicPric: true
      }
    ]
    if (score_consumption.value) {
      orderData.value.scoreMoney = score_consumption.value
    }
  }
}

//获取用户信息
const getUserDetailInfo = async () => {
  try {
    const { data } = await userApi.userInfo()
    console.log('用户数据', data)

    if (data && data.phone) {
      userPhone.value = data.phone
    } else {
      userPhone.value = ''
    }
    createTime.value = data.createTime

  } catch (error) {
    console.error('获取用户信息失败', error)
    userPhone.value = ''
  }
}

// 更新用户信息的模式
async function updateUserInfo() {
  if (mode.value == 3381) {
    uni.setStorageSync('hyType', JSON.stringify({ name: '花了还有', id: 1 }))
  } else if (mode.value == 3382) {
    uni.setStorageSync('hyType', JSON.stringify({ name: '鑫复来', id: 4 }))
  } else {
    uni.setStorageSync('hyType', JSON.stringify({ name: '黑银', id: 0 }))
  }

  await userApi.userInfoUpdate({
    mode: mode.value
  })
}

async function getScore(walletRuleId: any) {
  const { data } = await moneyApi.walletInfo({
    walletRuleId
  })
  if (walletRuleId == 2013) {
    hjfUserScor.value = Math.floor(data.money * 100) / 100
  } else {
    userScore.value = Math.floor(data.money * 10) / 10
    maxUserScor.value = Math.floor(data.money * 10) / 10
    _userScore = Math.floor(data.money * 10) / 10
  }
}

const getDeductionRate = (moneyRuleId: any) => {
  if (enumAll.MoneyRuleGroups.GROUP_25.ruleIds.includes(moneyRuleId)) {
    return enumAll.MoneyRuleGroups.GROUP_25.rate
  }
  if (enumAll.MoneyRuleGroups.GROUP_375.ruleIds.includes(moneyRuleId)) {
    return enumAll.MoneyRuleGroups.GROUP_375.rate
  }
  return 0.5
}

const scoreMax = computed(() => {
  if (!orderData) return 0
  if (money.value) {
    let _money = 0
    if (isHjfShop.value && whiteList.value) {
      _money = money.value * 0.5
    } else if (isHjfShop.value && !whiteList.value) {
      const rate = getDeductionRate(moneyRuleId.value)
      _money = money.value * rate
    }
    if (_money > maxUserScor.value) {
      return Math.floor(maxUserScor.value * 10) / 10
    } else {
      return Math.floor(_money * 10) / 10
    }
  } else {
    score_consumption.value = 0
    return 0
  }
})

async function getShopInfo() {
  try {
    const { data } = await productApi.getShopInfo({
      id: info.shopId,
      detail: true,
      otherColumns: 'moneyRuleDetails'
    })
    const { name, shopMoneyRules, code, user, integralsRuleId, specialStatus, shopMode } = data
    
    // 立即更新关键信息
    info.name = name
    mode.value = shopMode
    whiteList.value = specialStatus

    // 异步存储
    setTimeout(() => {
      uni.setStorageSync('shopCode', code)
      uni.setStorageSync('shopOwnerShareCode', user.shareCode)
    }, 0)

    // 延迟加载积分信息
    if (integralsRuleId == 1) {
      isHjfShop.value = true
      setTimeout(() => {
        getScore(enumAll.wallet_rule_id_enum.花积分钱包)
        getScore(enumAll.wallet_rule_id_enum.绿色积分钱包)
      }, 1000)
    }

    if (shopMoneyRules && shopMoneyRules.length > 0) {
      if (moneyRuleId.value) {
        const rule = shopMoneyRules.find(
          (item: { moneyRuleId: null }) => item.moneyRuleId == moneyRuleId.value
        )
        if (!rule) {
          info.shopMoneyRules = shopMoneyRules
          moneyRuleId.value = shopMoneyRules[0].moneyRuleId
        }
      } else {
        info.shopMoneyRules = shopMoneyRules
        moneyRuleId.value = shopMoneyRules[0].moneyRuleId
      }
    }
  } catch (error) {
    console.error('获取店铺信息失败:', error)
  }
}

// 防抖处理金额变化
const debouncedMoneyChange = debounce((newValue: string) => {
  if (newValue) {
    nextTick(() => {
      money.value = newValue.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    })
    if (newValue < 0) {
      uni.showToast({
        icon: 'none',
        title: '金额不能小于0'
      })
      money.value = 0
    } else {
      score_consumption.value = scoreMax.value
      userScore.value = Math.floor((maxUserScor.value - scoreMax.value) * 10) / 10
    }
  } else {
    userScore.value = Math.floor(maxUserScor.value * 10) / 10
  }
}, 300)

watch(money, debouncedMoneyChange)

// 合并相关监听器
watch([accessToken, () => userStore.hasLogin], async ([newToken, hasLogin]) => {
  if (newToken && hasLogin && info.shopId) {
    await getShopInfo()
  }
}, { immediate: false })

//跳转到绑定手机号
const toBindPhone = () => {
  uni.setStorageSync('currentUrl', window.location.href)
  uni.navigateTo({
    url: '/pages/physicalShopCheck/bindPhone'
  })
}

function radioGroupChange(e: any) {
  console.log(e)
}

//清空用户信息
const clearUser = () => {
  userStore.syncClearToken()
  userStore.syncClearUserInfo()
  const tempParams = getQueryObject(window.location.search)
  uni.navigateTo({
    url: `/pages/physicalShopCheck/hlhyPay?&qrcode=${tempParams.qrcode}&shopId=${tempParams.shopId}&shareCode=${tempParams.shareCode}`
  })
}

// 简化的微信登录
async function handleWeChatLogin(option: any) {
  try {
    await userStore.wxAuth()
    const codeAuth = getQueryVariable('code')
    if (codeAuth) {
      await userStore.wxWebLogin(codeAuth)
      const result: any = await userStore.hlhyLoginByOpenId()
      login_success.value = result
      
      if (result.status) {
        // 登录成功后异步获取用户信息
        setTimeout(() => {
          getUserDetailInfo()
          getShopInfo()
        }, 100)
      }
    }
  } catch (error) {
    console.error('微信登录失败:', error)
    uni.showToast({
      title: '登录失败，请重试',
      icon: 'none'
    })
  } finally {
    pageLoading.value = false
  }
}

// 统一的登录处理
async function handleLoginProcess(option: any) {
  try {
    if (userStore.hasLogin) {
      await getShopInfo()
      return
    }

    if (isWeChatBrowser.value) {
      pageLoading.value = true
      await handleWeChatLogin(option)
    } else {
      const tempParams = getQueryObject(window.location.search)
      uni.navigateTo({
        url: `/pages/login/index?&qrcode=${tempParams.qrcode}&shopId=${tempParams.shopId}&shareCode=${tempParams.shareCode}`
      })
    }
  } catch (error) {
    console.error('登录流程失败:', error)
    pageLoading.value = false
  }
}

// 获取店铺信息
function getMes(option: any) {
  if (!option) return

  const { shopId, moneyRuleId, money, color, deviceCode } = option
  info.shopId = shopId || ''
  moneyRuleId && (moneyRuleId.value = moneyRuleId)
  money && ((money.value = money), (inptDisabled.value = true))
  color && (btnColor.value = color)
}

// 监听 mode 和 createTime
watch(
  () => [mode.value, createTime.value],
  ([mode, createTime]) => {
    if (mode && createTime) {
      const userCreateTimeMs = createTime * 1000;
      const fiveMinutesAgoMs = Date.now() - 5 * 60 * 1000
      if (userCreateTimeMs > fiveMinutesAgoMs) {
        updateUserInfo()
      }
    }
  }
)

// 监听登录状态和手机号
watch(
  () => login_success.value.status,
  (newStatus) => {
    if (newStatus) {
      getUserDetailInfo()
    } else {
      bindPhone.value = false
    }
  },
  { immediate: true }
)

watch(
  userPhone,
  (newPhone) => {
    if (login_success.value.status) {
      if (newPhone === null) {
        bindPhone.value = false
      } else {
        bindPhone.value = !newPhone || newPhone.trim() === ''
      }
    }
  },
  { immediate: true }
)

// 优化后的 onLoad
onLoad(async (option) => {
  // 立即显示页面基础结构
  getMes(option)
  
  // 异步处理登录
  setTimeout(() => {
    handleLoginProcess(option)
  }, 0)
  
  // 预加载用户信息（非阻塞）
  if (userStore.hasLogin) {
    setTimeout(() => {
      getUserDetailInfo()
    }, 500)
  }
})
</script>

<style lang="scss" scoped>
.physicalShopCheck {
  padding: 30rpx;
  text-align: center;
  background: linear-gradient(#fab791 0%, rgba(255, 250, 224, 0) 30%);
  transform: translateZ(0);
  backface-visibility: hidden;
  perspective: 1000;

  .loading-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    
    .loading-text {
      margin-top: 20rpx;
      color: #666;
      font-size: 28rpx;
    }
  }

  .topTitLe {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;

    .leftTitle {
      text-align: left;
    }

    .rightTitle {
      image {
        will-change: transform;
      }
    }
  }

  .shopBox {
    min-height: 300rpx;
    padding: 20rpx;
    background: url('@/static/pay1.png') no-repeat;
    background-size: 100% 100%;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);

    .name {
      text-align: center;
      margin-top: 20rpx;
      font-size: 32rpx;
      font-weight: bold;
    }
  }

  .inptBox {
    display: flex;
    justify-content: center;
    align-items: flex-end;
    padding: 20rpx 0;
    border-top: 1px solid #8080802e;
    border-bottom: 1px solid #8080802e;
    position: relative;
    margin-top: 40rpx;
    font-size: 50rpx;

    .unit {
      right: 0;
      top: 36rpx;
      font-size: 28rpx;
      margin-bottom: 10rpx;
    }
  }

  .yt-list-cell {
    display: flex;
    align-items: center;
    padding: 40rpx 0;
    position: relative;

    .cell-tit {
      flex: 1;
      font-size: 26rpx;
      color: #909399;
      text-align: left;

      .red {
        color: #ff6c18;
      }
    }

    &.shape2 {
      display: block;

      .cell-tip {
        display: flex;
        justify-content: space-between;
        margin-top: 20rpx;
        align-items: center;

        .wallet {
          font-size: 28rpx;
          color: #ff6c18;
        }
      }
    }
  }

  .hjfScore {
    margin-top: 10rpx;
    text-align: left;
    color: #909399;
  }

  .radioBox {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 40rpx;

    :deep(.u-radio) {
      justify-content: center;
    }
  }

  .hy-btn {
    margin-top: 50rpx;
  }

  .hy-link {
    margin-top: 30rpx;
    text-align: right;
    color: #909399;
    text-decoration: underline;
  }
}

.inputBox {
  // 原有样式
}
</style>